const inquirer = require('inquirer')
const qiniu = require('gulp-up-cdn/qiniu')
const oss = require('gulp-up-cdn/oss')
const log = require('gulp-up-cdn/log')
const packageJson = require('./package.json')

const ANSWERS = {} // 问卷选择值
const PREFIX = `assets/${packageJson.name}` // 前缀
const UPLOAD_CONFIG = {} // cdn 配置
let upload_type = null // 上传类型

inquirerEnv()

/**
 * 环境选择
 */
function inquirerEnv() {
  inquirer.prompt([{
    type: 'list',
    message: '请选择(环境)>',
    name: 'env',
    choices: getEnvList(),
    filter: (val) => {
      return val
    }
  }]).then((answers) => {
    ANSWERS.env = answers.env
    getUploadConfig()
    getCatalogueByPrefix(1, `${PREFIX}/${ANSWERS.env}`, (list) => {
      inquirerFolder(list)
    })
  })
}

/**
 * 删除文件夹选择
 * @param {Array} selectList 备选列表
 */
function inquirerFolder(selectList) {
  if (selectList.length === 0) {
    log.popurse('没有可以删除的文件夹')
    return false
  }
  inquirer.prompt([{
    type: 'list',
    message: '请选择(要删除的文件夹)>',
    name: 'folder',
    choices: selectList,
    filter: (val) => {
      return val
    }
  }]).then((answers) => {
    getCatalogueByPrefix(2, `${PREFIX}/${ANSWERS.env}/${answers.folder}`, (list) => {
      switch (upload_type) {
      case 'qiniu':
        for (const item of list) {
          qiniu.delete(UPLOAD_CONFIG, item)
        }
        break
      case 'oss':
        for (const item of list) {
          oss.delete(UPLOAD_CONFIG, item)
        }
        break
      default:
        log.popurse('没有匹配环境')
        break
      }
    })
  })
}

/**
 * 根据路径前缀获取文件夹或文件列表
 * @param {String} type 类型 1文件夹 2文件
 * @param {String} prefix 资源前缀
 * @param {Function} callback 回调
 */
function getCatalogueByPrefix(type, prefix, callback) {
  const params = { prefix }
  switch (upload_type) {
  case 'qiniu':
    log.green('当前环境的CDN>>>七牛································')
    params['limit'] = 1000
    qiniu.get(UPLOAD_CONFIG.bucket, UPLOAD_CONFIG, params, (res) => {
      let list = []
      if (type === 1) {
        // 获取目录列表
        res.map((item) => {
          list.push(item.key.split(params.prefix)[1].split('/')[1])
        })
        list = Array.from(new Set(list))
      } else {
        res.map((item) => {
          list.push(item.key)
        })
      }
      callback(list)
    })
    break
  case 'oss':
    log.green('当前环境的CDN>>>阿里云OSS···························')
    params['max-keys'] = 1000
    log.green('资源获取中，请稍后···')
    oss.get(UPLOAD_CONFIG, params, (res) => {
      let list = []
      if (type === 1) {
        // 获取目录列表
        res.objects.map((item) => {
          list.push(item.name.split(params.prefix)[1].split('/')[1])
        })
        list = Array.from(new Set(list))
      } else {
        res.objects.map((item) => {
          list.push(item.name)
        })
      }
      callback(list)
    })
    break
  default:
    log.yellow('没有匹配环境')
    break
  }
}

/**
 * 获取环境配置列表
 */
function getEnvList() {
  const list = []
  for (const key in packageJson.envConfig) {
    if (key !== 'dev') {
      list.push(key)
    }
  }
  return list
}

/**
 * cdn 配置赋值
 */
function getUploadConfig() {
  const env_config = packageJson.envConfig[ANSWERS.env]
  // 七牛
  if (env_config.QN) {
    upload_type = 'qiniu'
    UPLOAD_CONFIG.accessKey = 'lb5ntuPzvl6BoSqL5yato8Pqwg5WXoPHGVzTktIt'
    UPLOAD_CONFIG.secretKey = '7i3g_SDTFCvJ-TYs3FBfCJJtki8Rp2hYfNVIK908'
    UPLOAD_CONFIG.bucket = env_config.QN.bucket
    UPLOAD_CONFIG.prefix = env_config.QN.prefix
  } else if (env_config.OSS) {
    upload_type = 'oss'
    UPLOAD_CONFIG.accessKeyId = 'LTAI5tBMtPLGbpwB7psTjgad'
    UPLOAD_CONFIG.accessKeySecret = 'bhZroRSfIuKDP3jueuOcjYwX2NxxOv'
    UPLOAD_CONFIG.bucket = env_config.OSS.bucket
    UPLOAD_CONFIG.region = env_config.OSS.region
    UPLOAD_CONFIG.prefix = env_config.OSS.prefix
  }
}
